﻿using CKS.Core.Framework;
using FreeSql;
using System.Security.Cryptography;
using ZR.Infrastructure.Helper;
using ZR.Model.Models.ProductionControl;
using LogHelper = ZR.Infrastructure.Helper.LogHelper;

namespace CKS.PLC.Action.OP10
{
    /// <summary>
    /// 
    /// 达因划线结果上传请求 
    ///    收到上传请求 
    ///     1:保存数据
    ///     0:复位状态
    /// </summary>
    public class Cks30Action : PLCAction
    {
        public Cks30Action(DecodeValue _value) : base(_value)
        {
        }

        public override void Execute()
        {
            var result =Value.Value.ToInt();
            if (result == 1)
            {
                //保存数据
                //读取子篮二维码和检测结果
                string barcode = Value.GetLinkData(1).ToString();
                int flag = Value.GetLinkData(2).ToInt();
                LogHelper.WritePlcLog($"保存数据 子篮码{barcode} 检测结果{flag}");


                CksBasketDyneRecord basketrecord = new CksBasketDyneRecord();
                basketrecord.BlueCode = barcode;
                basketrecord.CheckResult = flag;
                basketrecord.Type = GetPartType(barcode);
                basketrecord.CheckTime = DateTime.Now;

                conn.Insert(basketrecord).ExecuteAffrows();

                // 查询零件信息，增加已清洗数量（即可用数量）
                var part = conn.Select<CksPart>().Where(a => a.PartType == basketrecord.Type).First();
                conn.Update<CksPart>().Set(a => a.CleaningQuantity == a.CleaningQuantity + part.BlueCount)
                        .Where(it => it.Id == part.Id)
                        .ExecuteAffrows();

                //查找保存完成点位
                var replayPos = Value.GetPosition(3010,10);
                AckWriteInt16(replayPos,1);

                EventBus.AddLog($"OP10-达因检测 {barcode} 保存");

            }
            else
            {
                var replayPos = Value.GetPosition(3010, 10);
                AckWriteInt16(replayPos, 0);
            
                EventBus.AddLog($"OP10-达因检测 重置保存状态");
            }
        }


       


    }
}
